package com.nsl.my_youlai.controller;



import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nsl.my_youlai.common.result.PageResult;
import com.nsl.my_youlai.common.result.Result;
import com.nsl.my_youlai.common.utils.ExcelUtils;
import com.nsl.my_youlai.model.entity.SysUser;
import com.nsl.my_youlai.model.form.UserForm;
import com.nsl.my_youlai.model.query.UserPageQuery;
import com.nsl.my_youlai.model.vo.UserExportVO;
import com.nsl.my_youlai.model.vo.UserImportVO;
import com.nsl.my_youlai.model.vo.UserInfoVO;
import com.nsl.my_youlai.model.vo.UserPageVO;
import com.nsl.my_youlai.mystar.NslUtilFilePath;
import com.nsl.my_youlai.mystar.NslUtilUuid;
import com.nsl.my_youlai.plugin.UserImportListener;
import com.nsl.my_youlai.service.SysUserService;
import com.spire.doc.Document;
import exception.TemplateErrorException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import service.FillDocxTemplateWithExcelInformationService;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService userService;
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        log.info("in SysUserController.getCurrentUserInfo()");
        log.info("in SysUserController:  SysUserService userService = {}",userService);
        UserInfoVO userInfoVO = userService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }

    @GetMapping("/page")
    public PageResult<UserPageVO> getUserPage(
            UserPageQuery queryParams
    ) {

        log.info("queryParams = {}",queryParams);
        IPage<UserPageVO> result = userService.getUserPage(queryParams);
        return PageResult.success(result);
    }

    @PostMapping
    public Result saveUser(
            @RequestBody UserForm userForm
    ) {
        boolean result = userService.saveUser(userForm);
        return Result.judge(result);
    }

    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(
            @PathVariable Long userId
    ) {
        UserForm formData = userService.getUserFormData(userId);
        return Result.success(formData);
    }

    @PutMapping(value = "/{userId}")
    public Result updateUser(
            @PathVariable Long userId,
            @RequestBody @Validated UserForm userForm) {
        boolean result = userService.updateUser(userId, userForm);
        return Result.judge(result);
    }

    @DeleteMapping("/{ids}")
    public Result deleteUsers(
            @PathVariable String ids
    ) {
        boolean result = userService.deleteUsers(ids);
        return Result.judge(result);
    }

    @PatchMapping(value = "/{userId}/status")
    public Result updateUserStatus(
            @PathVariable Long userId,
            @RequestParam Integer status
    ) {

        boolean result = userService.update(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getId, userId)
                .set(SysUser::getStatus, status)
        );
        return Result.judge(result);
    }

    @PatchMapping(value = "/{userId}/password")
    public Result updatePassword(
            @PathVariable Long userId,
            @RequestParam String password
    ) {
        boolean result = userService.updatePassword(userId, password);
        return Result.judge(result);
    }

    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @PostMapping("/_import")
    public Result importUsers( Long deptId, MultipartFile file) throws IOException, TemplateErrorException, InvalidFormatException {
        UserImportListener listener = new UserImportListener(deptId);
        //获取原始文件名 - 1.jpg  123.0.0.jpg
        String originalFilename = file.getOriginalFilename();

        //构造唯一的文件名 (不能重复) - uuid(通用唯一识别码) de49685b-61c0-4b11-80fa-c71e95924018
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFileName = NslUtilUuid.generateUuidWithOutHyphen() + extname;
        log.info("新的文件名: {}", newFileName);

        //将文件存储在服务器的磁盘目录中 E:\images
        File savedFile=new File("D:\\Java_Projects\\Test\\Upload\\"+newFileName);
        file.transferTo(savedFile);

        String classPath=this.getClass().getResource("/").getPath().substring(1);
        log.info("classPath = {} ",classPath);

        String docxTemplatePath=classPath+"docx/设计模板(Demo).docx";
        String infoExcelPath=classPath+"docx/填充信息表格_v1 - 安阳.xlsx";
        docxTemplatePath= NslUtilFilePath.getFilePathBasedOnClassPath("docx/设计模板(Demo).docx");
        infoExcelPath= NslUtilFilePath.getFilePathBasedOnClassPath("docx/填充信息表格_v1 - 安阳.xlsx");
        //String infoExcelPath="d:\\填充信息表格_v1 - 安阳.xlsx";
        log.info("docxTemplatePath = {} ",docxTemplatePath);
        log.info("infoExcelPath = {} ",infoExcelPath);
        String outputFilePath="D:\\Java_Projects\\Test\\"+getTimeStamp()+".docx";
        buildDocx(docxTemplatePath,infoExcelPath,outputFilePath);


        String msg = ExcelUtils.importExcel(new FileInputStream(savedFile), UserImportVO.class, listener);
        return Result.success(msg);
    }

    @GetMapping("/_export")
    public void exportUsers(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "用户列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<UserExportVO> exportUserList = userService.listExportUsers(queryParams);
        EasyExcel.write(response.getOutputStream(), UserExportVO.class).sheet("用户列表")
                .doWrite(exportUserList);
    }

    public void buildDocx(String docxTemplatePath,String infoExcelPath,String outputFilePath) throws IOException, TemplateErrorException, InvalidFormatException {
        Document templateDocument=new Document(docxTemplatePath);

        //Document currentDocument=templateDocument.deepClone();
        FillDocxTemplateWithExcelInformationService convertService=new FillDocxTemplateWithExcelInformationService(templateDocument,infoExcelPath,outputFilePath);
        convertService.runOnce();
        // currentDocument.dispose();
        templateDocument.dispose();
    }

    //形式
    public String getTimeStamp(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_ HH-mm-ss_SSS"); // 设置格式
        Long currentTime = System.currentTimeMillis();  // 获取当前时间戳
        String timeString = format.format(currentTime);  // 时间戳转为时间格式
        return timeString;
    }

}
